//
//  AppDelegate.m
//  YSSmartHome
//
//  Created by Yahaong on 16/8/10.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "AppDelegate.h"
#import "TabBarController.h"
#import "LoginOrRegisterViewController.h"
#import "RegisterNavigationController.h"
#import "DataBaseManager.h"
#import "DataManager.h"
#import "TempViewController.h"
#import "ZTNetTest.h"
#import "MQTTCoverTool.h"
#import "JPUSHService.h"
#import "GlobalConst.h"
#import <XAISDK/XAI.h>
#import <XAISDK/XAILUIDUtil.h>
#import "CommonUtils.h"
#import "ApplicationHandler.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

static NSString * const kZTJPUSHSERVICEAPPKEY = @"72a591946a36b83cafeb5f6f";
static NSString * const kZTJPUSHSERVICECHANNEL = @"App Store";
#ifdef DEBUG
// 开发 极光FALSE为开发环境
static BOOL const kZTJPUSHSERVICEISPRODUCTION = FALSE;
#else
// 生产 极光TRUE为生产环境
static BOOL const kZTJPUSHSERVICEISPRODUCTION = TRUE;
#endif

@interface AppDelegate ()
<
JPUSHRegisterDelegate
>
@property (nonatomic, strong) ZTUser *m_user;
@property (nonatomic, strong) ZTNetTest *m_netTest;
@end

@implementation AppDelegate

#pragma mark - life cycle

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[ApplicationHandler shared] launching];
    [self setupNotification];
    [self setupJPushWithOptions:launchOptions];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self defaultController];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    debugLogInfo(@"applicationWillResignActive");
    if (kMQTTSessionManager.isLogin) {
        [kMQTTSessionManager.xai close];
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    debugLogInfo(@"applicationDidEnterBackground");
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    debugLogInfo(@"applicationWillEnterForeground");
    [[NSNotificationCenter defaultCenter]postNotificationName:kZTShowNavigationBarNotifKey object:nil];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [JPUSHService setBadge:0];
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    if (kMQTTSessionManager.isLogin) {
        [self relogin];
    }
}

- (void)applicationWillTerminate:(UIApplication *)application {

}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if ( self.allowRotation) {
        return  UIInterfaceOrientationMaskAllButUpsideDown;
    }
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark - notif
- (void)switchRootViewController:(NSNotification *)notif {
    NSInteger i = [notif.object integerValue];
    if (1 == i)
    {
        [UIView transitionWithView:[[UIApplication sharedApplication].delegate window]
                          duration:0.5
                           options:UIViewAnimationOptionTransitionCrossDissolve
                        animations:^{
                            BOOL oldState=[UIView areAnimationsEnabled];
                            [UIView setAnimationsEnabled:NO];
                            self.window.rootViewController = [[TabBarController alloc]init];
                            [UIView setAnimationsEnabled:oldState];
                        }
                        completion:NULL];
    }
    else if (2 == i)
    {
        LoginOrRegisterViewController * rootVc = [[LoginOrRegisterViewController alloc]init];
        RegisterNavigationController *nav = [[RegisterNavigationController alloc]initWithRootViewController:rootVc];
        [UIView transitionWithView:[[UIApplication sharedApplication].delegate window]
                          duration:0.4
                           options:UIViewAnimationOptionTransitionCrossDissolve
                        animations:^{
                            BOOL oldState=[UIView areAnimationsEnabled];
                            [UIView setAnimationsEnabled:NO];
                            self.window.rootViewController =  nav;
                            [UIView setAnimationsEnabled:oldState];
                        }
                        completion:NULL];
    }
}

- (void)switchRootViewLoginController
{
    LoginOrRegisterViewController * rootVc = [[LoginOrRegisterViewController alloc]init];
    RegisterNavigationController *nav = [[RegisterNavigationController alloc]initWithRootViewController:rootVc];
    self.window.rootViewController = nav;
}


#pragma mark - private method

- (void)defaultController {
    [self startLogin:YES];
}

- (void)relogin {
    [self startLogin:NO];
}

- (void)startLogin:(BOOL)isFirst {
    ZTUser *user = [ZTUser unarchiver];
    self.m_user = user;
    if (user.m_strTel.length == 0 || user.m_strPwd.length == 0) {
        LoginOrRegisterViewController * rootVc = [[LoginOrRegisterViewController alloc]init];
        RegisterNavigationController *nav = [[RegisterNavigationController alloc]initWithRootViewController:rootVc];
        self.window.rootViewController =  nav;
    } else {
        if (isFirst) {
            UINavigationController * nc = [[UINavigationController alloc]initWithRootViewController:[[TempViewController alloc]init]];
            self.window.rootViewController = nc;
        }
        XAI* xai = [[XAI alloc]initWithHost:kZTMQTTBaseURL port:kZTMQTTBasePort];
        xai.delegate = kMQTTSessionManager;
        kMQTTSessionManager.xai = xai;
        [xai startWithAccount:user.m_strTel password:user.m_strPwd success:^{
            kMQTTSessionManager.isLogin = YES;
            kMQTTSessionManager.currentUser = self.m_user;
            [kMQTTSessionManager.currentUser archiver];
            if (isFirst) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self animationSwitchRootController:[[TabBarController alloc]init]];
                });
            }
        } error:^(NSUInteger code) {
            debugLogInfo(@"登录失败");
            kMQTTSessionManager.isLogin = NO;
            [kMQTTSessionManager.xai close];
            dispatch_async(dispatch_get_main_queue(), ^{
                LoginOrRegisterViewController *rootVc = [[LoginOrRegisterViewController alloc]init];
                RegisterNavigationController *nav = [[RegisterNavigationController alloc]initWithRootViewController:rootVc];
                self.window.rootViewController =  nav;
            });
        }];
    }
}

- (void)animationSwitchRootController:(UIViewController*)controller {
    [UIView transitionWithView:[[UIApplication sharedApplication].delegate window]
                      duration:0.5
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
                        BOOL oldState=[UIView areAnimationsEnabled];
                        [UIView setAnimationsEnabled:NO];
                        self.window.rootViewController = controller;
                        [UIView setAnimationsEnabled:oldState];
                    }
                    completion:NULL];
}

#pragma mark- JPUSHRegisterDelegate

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        debugLogInfo(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
        //      [rootViewController addNotificationCount];
    }
    else {
        // 判断为本地通知
        debugLogInfo(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {

    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容

    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题

    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        debugLogInfo(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
        //        [rootViewController addNotificationCount];
    }
    else {
        // 判断为本地通知
        debugLogInfo(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler();  // 系统要求执行这个方法
}
#endif
// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

//注册
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [JPUSHService registerDeviceToken:deviceToken];
}
//注册失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificwationsWithError:(NSError *)error
{
    debugLogInfo(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

//接收
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // apn 内容获取：
    // 取得 APNs 标准信息内容
    //    [JPUSHService handleRemoteNotification:dict];
}
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

}

- (void)getRigisterID
{
    NSString *registerID = [JPUSHService registrationID];
    debugLogInfo(@"getRigisterID = %@",registerID);
    kMQTTSessionManager.registerID = registerID;
}

#pragma mark - setup
- (void)setupNotification {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(switchRootViewController:) name:kZTSwitchRootViewControllerKey object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(switchRootViewLoginController) name:kZTLoginEoorOrTimeOutNotifKey object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(switchRootViewLoginController) name:kZTExitLoginNotification object:nil];
}

- (void)setupJPushWithOptions:(NSDictionary *)launchOptions
{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) // iOS10
    {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity *entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = (UNAuthorizationOptionAlert  | UNAuthorizationOptionSound);
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
    {
        // categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    [JPUSHService setupWithOption:launchOptions appKey:kZTJPUSHSERVICEAPPKEY
                          channel:kZTJPUSHSERVICECHANNEL
                 apsForProduction:kZTJPUSHSERVICEISPRODUCTION
            advertisingIdentifier:nil];

    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0)
        {
            debugLogInfo(@"registrationID获取成功：%@",registrationID);
            kMQTTSessionManager.registerID = registrationID;
        }
        else
        {
            debugLogInfo(@"registrationID获取失败，code：%d",resCode);
        }
    }];
}

@end
